package cn.tedu.csmall.order.webapi.service.impl;


import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.OrderTb;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.IStockService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
@DubboService
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    RestTemplate restTemplate;

//    @Autowired
//    IStockService stockService;
    @DubboReference
    IStockService stockService;

    @DubboReference
    ICartService iCartService;


    @Override
    @GlobalTransactional
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // todo 1.减少订单商品的库存数(要调用stock模块的方法)
//     模拟StockReduceCountDTO 数据--做初始化调用 去使用
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        //通过restTemplate对象进行远程调用
        //第一个参数：要远程调用的模块的方法对应的路径
        //第二个参数：传入协议体内容
        //第三个参数：调用的方法返回值类型
//        restTemplate.postForObject(
//                "http://stock/base/stock/reduce/count",
//                stockReduceCountDTO,
//                JsonResult.class);
        stockService.reduceCommodityCount(stockReduceCountDTO);
        System.out.println("order实现调用stock");

        // todo 2.删除订单中勾选的购物车中的商品(要调用cart模块的方法)
        iCartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        System.out.println("order实现调用cart");
        // 3.新增订单
        OrderTb order=new OrderTb();
        BeanUtils.copyProperties(orderAddDTO,order);
        // 执行新增
       int row = orderMapper.insertOrder(order);
       if (row==0){
           throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"生成订单失败");
       }
//       if (Math.random()>0){
//           throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"网络问题");
//       }
        log.info("新增的订单信息:{}",order);
    }
}
